package handler

import (
	"context"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/types/known/emptypb"
	"mxshop_srvs/goods_srv/global"
	"mxshop_srvs/goods_srv/model"
	"mxshop_srvs/goods_srv/proto"
)

// 轮播图接口
// BannerList 获取轮播图列表
func (g *GoodsServer) BannerList(ctx context.Context, in *emptypb.Empty) (*proto.BannerListResponse, error) {
	// 实现获取轮播图列表的逻辑
	bannerListResponse := proto.BannerListResponse{}
	var banners []model.Banner
	result := global.DB.First(&banners)
	bannerListResponse.Total = int32(result.RowsAffected)
	var bannerResponses []*proto.BannerResponse
	for _, banner := range banners {
		bannerResponse := proto.BannerResponse{
			Id:    banner.ID,
			Index: banner.Index,
			Url:   banner.Url,
		}
		bannerResponses = append(bannerResponses, &bannerResponse)
	}
	bannerListResponse.Data = bannerResponses
	return &bannerListResponse, nil
}

// CreateBanner 创建轮播图
func (g *GoodsServer) CreateBanner(ctx context.Context, in *proto.BannerRequest) (*proto.BannerResponse, error) {
	// 实现创建轮播图的逻辑
	banner := model.Banner{}
	banner.Image = in.Image
	banner.Index = in.Index
	banner.Url = in.Url
	global.DB.Save(&banner)
	return &proto.BannerResponse{Id: banner.ID}, nil
}

// DeleteBanner 删除轮播图
func (g *GoodsServer) DeleteBanner(ctx context.Context, in *proto.BannerRequest) (*emptypb.Empty, error) {
	// 实现删除轮播图的逻辑
	if result := global.DB.Delete(&model.Banner{}, in.Id); result.RowsAffected == 0 {
		return nil, status.Error(codes.NotFound, "轮播图不存在")
	}
	return &emptypb.Empty{}, nil
}

// UpdateBanner 更新轮播图
func (g *GoodsServer) UpdateBanner(ctx context.Context, in *proto.BannerRequest) (*emptypb.Empty, error) {
	// 实现更新轮播图的逻辑
	var banner model.Banner
	if result := global.DB.First(&banner, in.Id); result.RowsAffected == 0 {
		return nil, status.Error(codes.NotFound, "轮播图不存在")
	}
	if in.Index != 0 {
		banner.Index = in.Index
	}
	if in.Image != "" {
		banner.Image = in.Image
	}
	if in.Url != "" {
		banner.Url = in.Url
	}
	global.DB.Save(&banner)
	return &emptypb.Empty{}, nil
}
